package com.pay.manager;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pay.common.response.Response;
import com.pay.common.util.DateFormatUtil;
import com.pay.common.util.ExcelUtils;
import com.pay.common.util.MD5Util;
import com.pay.common.util.SqlUtil;
import com.pay.dao.entity.*;
import com.pay.dao.mapper.LogInfoMapper;
import com.pay.dao.mapper.ProductionMapper;
import com.pay.dao.mapper.UserInfoMapper;
import com.pay.dao.mapper.ViewLogMapper;
import com.pay.dao.mapper.ext.ProductionMapperExt;
import com.pay.dto.domain.*;
import com.pay.dto.request.*;
import com.pay.dto.response.ProductionSelectRespDto;
import com.pay.service.TokenUntil;
import com.pay.service.WebSocketServer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Component
public class WareHouseManager {
    protected final Logger logger = LoggerFactory.getLogger(WareHouseManager.class);

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private ViewLogMapper viewLogMapper;

    @Autowired
    private ProductionMapper productionMapper;
    @Autowired
    private ProductionMapperExt productionMapperExt;

    @Autowired
    private TokenUntil tokenUntil;

    @Autowired
    private LogInfoMapper logInfoMapper;


    @Value("${file.errPath}")
    private String errPath;

    @Value("${file.logUrl}")
    private String logUrl;

    @Value("${file.picUrl}")
    private String picUrl;

    @Value("${file.errFileUrl}")
    private String errFileUrl;

    @Autowired
    private WebSocketServer webSocketServer;

    public Response sendPic(SendPicReqDto sendPicReqDto) throws Exception{
        ProductionExample example = new ProductionExample();
        example.createCriteria().andProductionIdEqualTo(sendPicReqDto.getProductionId());
        List<Production> productionsList = productionMapper.selectByExample(example);
        LogInfo logInfo = new LogInfo();
        logInfo.setProductionId(sendPicReqDto.getProductionId());
        if(productionsList==null||productionsList.size()<=0){
            logInfo.setRemark("系统中不存在条码号！");
            logInfo.setCreatedDate(new Date());
            logInfo.setUpdatedDate(new Date());
            logInfoMapper.insert(logInfo);
            return Response.fail("系统中不存在条码号！");
        }
        Production production = productionsList.get(0);
        String msg= picUrl+ productionsList.get(0).getImageName();
        Map map = new HashMap();
        map.put("productionId",production.getProductionId());
        map.put("productionName",production.getProductionName());
        map.put("imageName",msg);

        //保存浏览记录
        ViewLog viewLog = new ViewLog();
        viewLog.setProductionId(production.getProductionId());
        viewLog.setProductionName(production.getProductionName());
        viewLog.setRemark(production.getImageName());
        viewLog.setCreatedDate(new Date());
        viewLog.setUpdatedDate(new Date());
        viewLogMapper.insert(viewLog);

        logInfo.setProductionName(production.getProductionName());
        logInfo.setImageName(production.getImageName());
        logInfo.setImagePath(msg);
        logInfo.setCreatedDate(new Date());
        logInfo.setUpdatedDate(new Date());
        webSocketServer.BroadCastInfo(msg);
        logInfoMapper.insert(logInfo);
        return Response.success("推送成功",map);
    }

    public Response query(ProductionSelectReqDto productionSelectReqDto){
        startPage();
        List<ProductionSelectRespDto> productionSelectRespDtoList =
                productionMapperExt.productionQuery(productionSelectReqDto);
        ResponsePageDto dataTable = getDataTable(productionSelectRespDtoList);
        return Response.success("成功",dataTable);

    }
    public Response viewLogquery(ViewLog viewLog){
        startPage();
//        List<ProductionSelectRespDto> productionSelectRespDtoList =
//                productionMapperExt.productionQuery(productionSelectReqDto);
//        ResponsePageDto dataTable = getDataTable(productionSelectRespDtoList);
        //todo 无
        return Response.success("成功");

    }

    public Response delete(List<ProductionDeleteReqDto> productionDeleteReqDtoList){
        for (ProductionDeleteReqDto i:productionDeleteReqDtoList){
            Long id=0L;
            try {
              id=Long.parseLong(i.getId());
            }catch (Exception e){
                return Response.fail("传入的主键只能是数字！");
            }
            productionMapper.deleteByPrimaryKey(id);
        }
        return Response.success("删除成功");
    }

    public Response insert(ProductionInsertDto productionInsertDto,HttpServletRequest request){
        UserInfo userInfo=tokenUntil.getUserbyToken(request);
        if(userInfo==null){
           return Response.fail("-1","您还没有登录或登录已超时，请重新登录！",null);
        }
        if(StringUtils.isBlank(productionInsertDto.getId())){
            ProductionExample example = new ProductionExample();
            example.createCriteria().andProductionIdEqualTo(productionInsertDto.getProductionId());
            List<Production> productionsList = productionMapper.selectByExample(example);
            if(productionsList!=null&&productionsList.size()>0){
                return Response.fail("系统中已经存在该条码号，不能修改重复了!");
            }
            Production production = new Production();
            BeanUtils.copyProperties(productionInsertDto,production);
            production.setUserId(userInfo.getId());
            production.setCreatedDate(new Date());
            production.setUpdatedDate(new Date());
            productionMapper.insert(production);
            return Response.success("新增成功");
        }else{
            //修改
            ProductionExample example = new ProductionExample();
            example.createCriteria()
                    .andProductionIdEqualTo(productionInsertDto.getProductionId())
                    .andIdNotEqualTo(Long.parseLong(productionInsertDto.getId()));
            List<Production> productionsList = productionMapper.selectByExample(example);
            if(productionsList!=null&&productionsList.size()>0){
                return Response.fail("系统中已经存在该条码号，不能重复录入!");
            }
            Production production =   productionMapper.selectByPrimaryKey(Long.parseLong(productionInsertDto.getId()));
            if(production==null){
                return Response.fail("该条记录已经不存在，请刷新系统，获取最新信息");
            }
            BeanUtils.copyProperties(productionInsertDto,production);
            production.setUpdatedDate(new Date());
            production.setYl1(userInfo.getId().toString());
            productionMapper.updateByPrimaryKey(production);
            return Response.success("修改成功");
        }
    }

    public Response login(LoginReqDto loginReqDto, HttpServletRequest request) throws Exception{
        UserInfoExample userInfoExample = new UserInfoExample();
        userInfoExample.createCriteria()
                .andUserNameEqualTo(loginReqDto.getUserName())
                .andPasswordEqualTo(MD5Util.MD5Encode(loginReqDto.getPassword(),"UTF-8"));
        List<UserInfo>  userInfoList =userInfoMapper.selectByExample(userInfoExample);
        if(userInfoList==null||userInfoList.size()<=0){
            return Response.fail("用户名或者密码错误");
        }
        Map map = new HashMap();
        UserInfo userInfo= userInfoList.get(0);
        String token=userInfo.getYl1();
        if(StringUtils.isBlank(token)){
            token= StringUtils.replace(UUID.randomUUID().toString(),"-","");
        }else{
            if(userInfo.getUpdatedDate().before(DateFormatUtil.getOneHouser())){
                token= StringUtils.replace(UUID.randomUUID().toString(),"-","");
            }
        }
        userInfo.setUpdatedDate(new Date());
        userInfo.setYl1(token);
        userInfoMapper.updateByPrimaryKey(userInfo);
        map.put("token",token);
        return Response.success("成功",map);
    }

    public Response importFile(List<ProductionFile> list, HttpServletRequest request){
        Boolean isSuccess=true;
        Production production=null;
        int errCount=0;
        Map map = new HashMap();
        UserInfo userInfo=tokenUntil.getUserbyToken(request);
        if(userInfo==null){
            return Response.fail("-1","您还没有登录或登录已超时，请重新登录！",null);
        }
        List<ProductionFileResult> resultList = new ArrayList<ProductionFileResult>();
        ProductionFileResult productionFileResult =null;
        for (ProductionFile i:list){
            StringBuffer errMsg=new StringBuffer();
            if(StringUtils.isBlank(i.getProductionId())){
                errMsg.append("条码号不能为空；");
                isSuccess=false;
            }
            if(StringUtils.isBlank(i.getProductionName())){
                errMsg.append("产品名称不能为空；");
                isSuccess=false;
            }
            if(StringUtils.isBlank(i.getImageName())){
                errMsg.append("图片编号不能为空；");
                isSuccess=false;
            }

            //判断是否存在
            if(StringUtils.isNotBlank(i.getProductionId())){
                ProductionExample example = new ProductionExample();
                example.createCriteria().andProductionIdEqualTo(i.getProductionId());
                List<Production> productionsList = productionMapper.selectByExample(example);
                if(productionsList!=null&&productionsList.size()>0){
                    errMsg.append("重复，系统中已经存在该条码号；");
                    isSuccess=false;
                }
            }

            if(StringUtils.isBlank(errMsg)){
                production = new Production();
                BeanUtils.copyProperties(i,production);
                production.setUserId(userInfo.getId());
                production.setCreatedDate(new Date());
                production.setUpdatedDate(new Date());
                productionMapper.insert(production);
                errMsg.append("成功");
            }else {
                errCount=errCount+1;
            }
            productionFileResult = new ProductionFileResult();
            BeanUtils.copyProperties(i,productionFileResult);
            productionFileResult.setErrMsg(errMsg.toString());
            resultList.add(productionFileResult);
        }
        logger.info("errCount-->"+errCount);
        //生成错误文件
        String errName="";
        if(!isSuccess){
           errName="错误文件明细信息"+ getSerialNo()+".xlsx";
           String path =errPath+errName;
           ExcelUtils.writeExcel(path,resultList,ProductionFileResult.class);
        }
        map.put("total",list.size());
        map.put("success",list.size()-errCount);
        map.put("fail",errCount);
        if(StringUtils.isNotBlank(errName)){
            map.put("errName",errFileUrl+errName);
        }else{
            map.put("errName","");
        }
        return Response.success("成功",map);
    }

    public Response downLogInfo(LogInfoReq logInfoReq){
        Map map = new HashMap();
        List<LogInfoDownResp> logInfoDownList = productionMapperExt.downLogInfo(logInfoReq);
        if(logInfoDownList==null||logInfoDownList.size()<=0){
            map.put("status","true");
            map.put("info","导出数据为空");
            map.put("path","");
            return Response.success("成功",map);
        }
        String logName="扫码记录";
        String path =logUrl+logName+logInfoReq.getStartDate()+"到"+logInfoReq.getEndDate()+"的明细"+getSerialNo1()+".xlsx";
        ExcelUtils.writeExcel(path,logInfoDownList,LogInfoDownResp.class);
        map.put("status","true");
        map.put("info","导出数据成功");
        map.put("path",path);
        return Response.success("成功",map);
    }

    public static String getSerialNo(){
        Random rd = new Random();
        String str="";
        while(str.length()<8){
            int temp =rd.nextInt(10);
            str+=temp;
        }
        return DateFormatUtil.getCurrentTime(DateFormatUtil.YYYYMMDDHHMMSS)+str;
    }
    public static String getSerialNo1(){
        Random rd = new Random();
        String str="";
        while(str.length()<8){
            int temp =rd.nextInt(10);
            str+=temp;
        }
        return str;
    }
    /**
     * 设置请求分页数据
     */
    protected void startPage()
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (pageNum!=null && pageSize!=null)
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    protected ResponsePageDto getDataTable(List<?> list)
    {
        ResponsePageDto responsePageDto = new ResponsePageDto();
        responsePageDto.setRowList(list);
        responsePageDto.setTotal(new PageInfo(list).getTotal()+"");
        return responsePageDto;
    }
}
